import {
  allowInviteList,
  inviteCardJoinGroup,
  getGroupMemberList,
  deleteGroupMember
} from '../../apis/group';
import {
  globalData
} from '../../utils/request';
const app = getApp();

Page({
  data: {
    master: {},
    selectedList: [],
    rankList: [],
    indexList: [],
    reasonValue: '',
    modalShow: false,
    inputValue: '',
    searchList: [],
    isSearch: false
  },

  onLoad(options) {
    this.setData({
      ...options,
      showGroupBtn: globalData.checkIn
    });
    if (options.type === 'preview') {
      wx.setNavigationBarTitle({
        title: '组成员'
      });
    } else if (options.type === 'edit') {
      wx.setNavigationBarTitle({
        title: '组管理'
      });
    };
    if (options.type === 'edit' || options.type === 'preview') this.getGroupMember(options.groupId, 1, 99999999);
    else if (options.type === 'invite') this.getCardList(options.groupId, '');
  },

  getCardList(id, keyword) {
    allowInviteList(id, keyword).then(res => {
      if (res.data.code === 200) {
        let {
          rows
        } = res.data;
        let indexList = [];
        rows.forEach(v => {
          indexList.push(v.userName.substr(0, 1).spell('first'));
        });
        indexList = [...new Set(indexList.sort())];
        let rankList = indexList.map(v => {
          return {
            rank: v,
            cardList: []
          }
        });
        rows.forEach(v => {
          rankList.forEach(val => {
            if (v.userName.substr(0, 1).spell('first') === val.rank) {
              if (v.images) {
                v.images = v.images.split(',');
                let arr = v.images.map(img => {
                  if (!new RegExp('^https://').test(img) && !new RegExp('^http://').test(img)) img = app.globalData.url + img;
                  return img
                });
                v.images = arr;
              };
              if (!new RegExp('^https://').test(v.avatar) && !new RegExp('^http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
              v.select = false;
              val.cardList.push(v);
            };
          });
        });
        this.setData({
          rankList: rankList,
          indexList: indexList
        });

        setTimeout(() => {
          this.getRankTop();
        }, 500);
      };
    });
  },

  getGroupMember(id, pageNum, pageSize) {
    getGroupMemberList(id, pageNum, pageSize).then(res => {
      if (res.data.code === 200) {
        let {
          rows
        } = res.data;

        // if (this.data.isOfficial != 1) {
        //   let master = rows[0];
        //   master.avatar = !new RegExp('^https://').test(master.avatar) && !new RegExp('^http://').test(master.avatar) ? app.globalData.url + master.avatar : master.avatar;
        //   rows.splice(0, 1);
        //   this.setData({
        //     master: master
        //   });
        // };

        let indexList = [];
        rows.forEach(v => {
          indexList.push(v.userName.substr(0, 1).spell('first'));
        });
        indexList = [...new Set(indexList.sort())];
        let rankList = indexList.map(v => {
          return {
            rank: v,
            cardList: []
          }
        });
        rows.forEach(v => {
          rankList.forEach(val => {
            if (v.userName.substr(0, 1).spell('first') === val.rank) {
              if (v.images) {
                v.images = v.images.split(',');
                let arr = v.images.map(img => {
                  if (!new RegExp('^https://').test(img) && !new RegExp('^http://').test(img)) img = app.globalData.url + img;
                  return img
                });
                v.images = arr;
              };
              if (!new RegExp('^https://').test(v.avatar) && !new RegExp('^http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
              v.select = false;
              val.cardList.push(v);
            };
          });
        });
        this.setData({
          rankList: rankList,
          indexList: indexList
        });

        setTimeout(() => {
          this.getRankTop();
        }, 500);
      };
    });
  },

  getRankTop() {
    let query = wx.createSelectorQuery();
    this.data.indexList.forEach(v => {
      query.select('#jump' + v).boundingClientRect();
    });
    query.exec(v => {
      this.setData({
        indexList: v
      });
    });
  },
  // 页面滚动
  jumpRank(e) {
    let {
      rank
    } = e.currentTarget.dataset;
    let query = wx.createSelectorQuery();
    query.select('.search-box').boundingClientRect(rect => {
      this.data.indexList.forEach(v => {
        if ('jump' + rank === v.id) {
          wx.pageScrollTo({
            duration: 300,
            scrollTop: v.top - rect.height
          });
        };
      });
    }).exec();
  },

  // 隐藏
  hideOverlay() {
    this.setData({
      modalShow: false
    });
  },

  // 输入理由
  inputReason(e) {
    let {
      value
    } = e.detail;
    this.setData({
      reasonValue: value
    });
  },

  // 选中
  selectCard(e) {
    let {
      rankindex,
      index
    } = e.currentTarget.dataset;
    this.data.rankList[rankindex].cardList[index].select = !this.data.rankList[rankindex].cardList[index].select;
    if (this.data.rankList[rankindex].cardList[index].select) {
      this.data.selectedList.push(this.data.rankList[rankindex].cardList[index]);
    } else {
      this.data.selectedList.splice(this.data.selectedList.findIndex(v => v.cardId === this.data.rankList[rankindex].cardList[index].cardId), 1);
    };
    this.setData({
      rankList: this.data.rankList,
      selectedList: this.data.selectedList
    });
  },

  previewCard(e) {
    let {
      rankindex,
      index
    } = e.currentTarget.dataset;
    let card = this.data.rankList[rankindex].cardList[index];
    wx.navigateTo({
      url: `/pages/groupCardPreview/index?type=group&groupId=${this.data.groupId}&card=${JSON.stringify(card)}`
    });
  },
  searchPreviewCard(e) {
    let {
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/cardPreview/index?cardId=' + id,
    });
  },

  confirm() {
    if (this.data.type === 'invite') {
      if (this.data.isMaster == 'true') {
        this.inviteCard('');
      } else if (this.data.isMaster == 'false' && this.data.isChecked == 1) {
        let str = JSON.stringify(this.data.selectedList);
        wx.navigateTo({
          url: `/pages/inviteDetails/index?inviteCard=${str}&reason=&groupId=${this.data.groupId}`
        });
      } else if (this.data.isMaster == 'false' && this.data.isChecked == 2) {
        this.setData({
          modalShow: true
        });
      };
    } else if (this.data.type === 'edit') {
      this.removeCard();
    };
  },
  confirmInvite() {
    let str = JSON.stringify(this.data.selectedList);
    wx.navigateTo({
      url: `/pages/inviteDetails/index?inviteCard=${str}&reason=${this.data.reasonValue}&groupId=${this.data.groupId}`
    });
  },

  inviteCard(reason) {
    let arr = this.data.selectedList.map(v => {
      return v.relCardId
    });

    inviteCardJoinGroup(this.data.groupId, arr, reason).then(res => {
      if (res.data.code === 200) {
        this.setData({
          modalShow: false
        });
        wx.showToast({
          title: '邀请成功',
          icon: 'success',
          mask: true,
          duration: 1500,
          success: res => {
            setTimeout(() => {
              wx.navigateBack({
                delta: 1
              });
            }, 1500);
          }
        });
      };
    });
  },

  handleInput(e) {
    let {
      value
    } = e.detail;
    this.setData({
      inputValue: value
    });
  },
  handleSearch() {
    let regExp = new RegExp(this.data.inputValue);
    let arr = [];
    this.data.rankList.forEach(v => {
      v.cardList.forEach(v => {
        if (regExp.test(v.phone) || regExp.test(v.userName) || regExp.test(v.labels) || regExp.test(v.company) || regExp.test(v.post)) {
          arr.push(v);
        };
      });
    });
    this.setData({
      isSearch: true,
      searchList: arr
    });
  },
  cancelSearch() {
    this.setData({
      inputValue: '',
      searchList: [],
      isSearch: false
    });
  },

  // 移除成员
  removeCard() {
    let arr = this.data.selectedList.map(v => {
      return v.cardId
    });
    wx.showModal({
      title: '确定移出吗？',
      success: res => {
        if (res.confirm) {
          deleteGroupMember(this.data.groupId, arr.join(',')).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '移出成功',
                icon: 'success',
                mask: true
              });
              this.getGroupMember(this.data.groupId, 1, 99999999);
            };
          });
        };
      }
    });
  }
})